package com.cbh.amadeus.client.utils;

import com.cbh.amadeus.client.receiver.service.MessageHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.TargetSource;
import org.springframework.aop.framework.Advised;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ChenBiHui
 * @date 2025/5/26
 */
@Slf4j
public class MessageHolderProxyChange {

    private static final Map<String, String> PROXY_CHANGE_CACHE = new ConcurrentHashMap<>(64);

    public static String get(MessageHolder<?> holder) {
        return PROXY_CHANGE_CACHE.computeIfAbsent(holder.getClass().getName(), key -> {
            String name;
            if (holder instanceof Advised) {
                try {
                    TargetSource target = ((Advised) holder).getTargetSource();
                    Object origin = target.getTarget();
                    if (origin != null) {
                        name = origin.getClass().getName();
                    } else {
                        log.warn("===== Proxy origin is null, can't get the target name, has used the proxy name =====");
                        name = holder.getClass().getName();
                    }
                } catch (Exception ignored) {
                    log.warn("===== Proxy get target error, has used the proxy name =====");
                    name = holder.getClass().getName();
                }
            } else {
                name = holder.getClass().getName();
            }
            return name;
        });
    }
}
